package com.sita.linboard.base;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.DebugUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.amap.api.maps.model.LatLng;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.NetUtils;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.sita.linboard.CmdOrderBean;
import com.sita.linboard.MainMessage.MainActivity;
import com.sita.linboard.MainMessage.PayInfoBackBean;
import com.sita.linboard.R;
import com.sita.linboard.RemindOrderActivity;
import com.sita.linboard.WelcomeActivity;
import com.sita.linboard.journey.UserLocation;
import com.sita.linboard.utils.Constants;
import com.sita.linboard.utils.LogUtils;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;

/**
 * Created by Jason on 2016/8/23.
 */
public abstract class BaseActivity extends Activity {
    private String TAG =getClass().getSimpleName();
    private int id;
    private EMMessageListener messageListener;
    private SoundPool soundPool;
    private CmdOrderBean  bean = new CmdOrderBean();
    private MyHandler handler = new MyHandler(this);
    private PayInfoBackBean payInfoBackBean;
    private static BaseActivity baseActivity;
    private MyConnectionListener myConnectionListener;

    static class MyHandler extends Handler {
        WeakReference<BaseActivity> thisActivity;

        MyHandler(BaseActivity activity){
            thisActivity = new WeakReference<BaseActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            final BaseActivity activity = thisActivity.get();
            switch (msg.what) {
                case 1:
                        activity.bean = (CmdOrderBean) msg.obj;
                        RemindOrderActivity.RemindOrderIntent(activity,activity.bean);
                    break;
                case 2:
                    Log.e(activity.TAG,"获取到支付消息");
                    Intent intent = new Intent("com.sita.linboard.PAYINFOMSG");
                    Bundle bundle = new Bundle();
                    activity.payInfoBackBean = (PayInfoBackBean) msg.obj;
                    bundle.putSerializable("payInfoMsg",activity.payInfoBackBean);
                    intent.putExtras(bundle);
                    activity.sendBroadcast(intent);
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getId());
        initView(savedInstanceState);
        EMClient.getInstance().addConnectionListener(myConnectionListener);
        initData();
        getMessageFromHX();
        long startTime = System.currentTimeMillis();
        final Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(startTime);
        Log.e(TAG,"onCreat");

        Log.e("sss",sHA1(this));
    }

    @Override
    protected void onStart() {
        super.onStart();
    }
    protected abstract void initData();

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract int getId();

    protected <T extends View> T bindView(int id) {
        return (T) findViewById(id);
    }

    public static void callToUser(Context context) {
        String mobile = SpUtils.getString("user_poone", "0", BaseApplication.getContext());
        Intent intentx = new Intent();
        intentx.setAction(Intent.ACTION_CALL);
        intentx.setData(Uri.parse("tel:" + mobile));
        context.startActivity(intentx);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        SpUtils.putBoolean("isReady",false,BaseApplication.getContext());
        long startTime = System.currentTimeMillis();
        final Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(startTime);
        Log.e("111111Base","onDestyoy");
    }
    private void getMessageFromHX() {
        messageListener = new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> list) {
            }
            @Override
            public void onCmdMessageReceived(List<EMMessage> list) {
                //乘客位置透传

                for (EMMessage message : list) {
                    EMCmdMessageBody body = (EMCmdMessageBody) message.getBody();
                    final String action = body.action();
                    if (!TextUtils.isEmpty(action)) {
                        LogUtils.d("Base", "收到透传消息"+"action = "+action);

                        switch (action) {
                            //===================================乘客位置信息透传
                            case "PUBLISHTRIP":
                                Message msg = new Message();
                                bean.setDepartureaddr(message.getStringAttribute("departureaddr",""));
                                bean.setArrivaladdr(message.getStringAttribute("arrivaladdr",""));
                                bean.setTime(message.getStringAttribute("time",""));
                                bean.setTripID(message.getStringAttribute("tripID",""));
                                LogUtils.e("111111Base","是否出车"+Constants.isReady);
                                if (Constants.isReady) {
                                    voice();
                                    msg.what = 1;
                                    msg.obj = bean;
                                    handler.sendMessage(msg);
                                }
                                else {
                                    handler.sendEmptyMessage(0);
                                }
                                break;
                            case "PAYINFORM":
                                Message payInfoMsg = new Message();
                                payInfoBackBean = new PayInfoBackBean();
                                if (message!=null||payInfoBackBean!=null){
                                    payInfoBackBean.setInformation(message.getStringAttribute("information",""));
                                    payInfoBackBean.setType(message.getStringAttribute("type",""));
                                    payInfoBackBean.setPaytime(message.getStringAttribute("paytime",""));
                                    payInfoBackBean.setAction(message.getStringAttribute("action",""));
                                    payInfoBackBean.setTripID(message.getStringAttribute("tripID",""));
                                    payInfoBackBean.setInformID(message.getStringAttribute("informID",""));
                                    payInfoMsg.what=2;
                                    payInfoMsg.obj = payInfoBackBean;
                                    handler.sendMessage(payInfoMsg);
                                }
                                else {
                                    handler.sendEmptyMessage(0);
                                    EventBus.getDefault().post("1");
                                }
                                break;
                        }
                    }
                }
            }

            @Override
            public void onMessageReadAckReceived(List<EMMessage> list) {
            }

            @Override
            public void onMessageDeliveryAckReceived(List<EMMessage> list) {
            }

            @Override
            public void onMessageChanged(EMMessage emMessage, Object o) {
            }

        };
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }
    private void voice(){
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM,5);
        soundPool.load(BaseApplication.getContext(), R.raw.order,1);
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                soundPool.play(1,1,1,1,0,1);
            }
        });
    }
    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
	   /*
	    * 可接受的电话格式有：
	    */
        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";
	   /*
	    * 可接受的电话格式有：
	    */
        String expression2 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);

        Pattern pattern2 = Pattern.compile(expression2);
        Matcher matcher2 = pattern2.matcher(inputStr);
        if(matcher.matches() || matcher2.matches()) {
            isValid = true;
        }
        return isValid;
    }
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }
        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(error == EMError.USER_REMOVED){
                        // 显示帐号已经被移除
                    }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        ToastUtils.show("222222",2);
                    } else {
                        if (NetUtils.hasNetwork(BaseActivity.this)){

                        }
                        //连接不到聊天服务器
                        else{
                            //当前网络不可用，请检查网络设置
                        }


                    }
                }
            });
        }
    }
    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

